public class SearchPageController_AC {
    public String fname{get; set;}
    public String lname{get; set;}
    //public String zip{get; set;}
    public String phoneNum{get; set;}
    public String email{get; set;}
    public boolean showResultsBlock = false;
    public list<AccountValues> AccList = new list<AccountValues>();
    public Boolean returntozipcode{get; set;}
    public Boolean returntoemail{get; set;}
    public Boolean returntophone{get; set;}
    public String tabname{get; set;}
    public boolean searchButtonEnable = true;
    public Boolean saveButtonEnable{get; set;}
    public boolean newButtonEnable{get; set;}
   
    public boolean reqFieldsEnable{get; set;}
    public boolean dispAccountList = false;
    public boolean errorOccured = false;
    public String state {get; set;}
    public String country {get; set;}
    // public boolean emailRequired{get; set;}
  //  public boolean phoneRequired{get; set;}
        

    public boolean getsearchButtonEnable(){
        return searchButtonEnable;
    }
    public boolean getShowResultsBlock(){
        return showResultsBlock;
    }
    public SearchPageController_AC(ApexPages.standardController controller){
        newButtonEnable=false;
        saveButtonEnable=false;
        reqFieldsEnable=false;
       // emailRequired=true;
     //  phoneRequired=true;
       // errorOccured=false;
        //acc=(Account)controller.getRecord();
       // userId=userInfo.getUserId();
    }
    public string getpbtitleValue(){
        if(!newButtonEnable){
            return 'Search Records';
        }
        else{
            return 'Create New Lead';
        }
    }


    public string getpbsectitleValue(){
        if(!newButtonEnable){
            return 'Enter at least one field';
        }
        else{
            return 'All fields other than Phone Number are Mandatory';
        }
    }

    public Pagereference search(){
        //zip='';
        list<Account> matchingAccounts = new list<Account>();
        list<Lead> matchingLeads = new list<Lead>();
        AccList.clear();
        
        /*RecordTypes*/
        String accountRecordType = Schema.Sobjecttype.Account.getRecordTypeInfosByName().get('West - Student Account').getRecordTypeId();
        String leadRecordType = Schema.Sobjecttype.Lead.getRecordTypeInfosByName().get('West - Prospective Student').getRecordTypeId();
        
        /*Flags*/
        boolean AccountDispFlag = false;
        saveButtonEnable = false;
        //returnToZipCode=false;
        returnToEmail = false;
        returnToPhone = false;

        /*Clearing spaces*/
        fname=fname.trim();
        lname=lname.trim();
        //zip = zip.trim();
        email = email.trim();
        phoneNum = phoneNum.trim();
        
        /*Checking for Mandatory Fields*/
        /*if(fname.length()<1 || lname.length()<1){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'First Name and Last Name are Mandatory Fields'));
                AccountDispFlag=true;
                DispAccountList = false;
                newButtonEnable = false;
                showResultsBlock = false;
                return null;
        }*/
        
        /*Check for pattern match and empty first Name and Last Name */ 
        if(fname!=''&& lname!='' && (!Pattern.matches('^[-a-zA-Z0-9.&#()/_\'\\s]+$', fname) || !Pattern.matches('^[-a-zA-Z0-9.&#()/_\'\\s]+$', lname))){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Name cannot contain these characters'));
                AccountDispFlag=true;
                DispAccountList = false;
                newButtonEnable = false;
                showResultsBlock = false;
                return null;
        }
        
        /*Check for non empty zip code but with wrong values*/
        /*if(zip!='' && (!Pattern.matches('^[0-9]+$', zip)||zip.length()!=5)){
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'ZIP Code should contain 5 digits'));
                AccountDispFlag=true;
                DispAccountList = false;
                newButtonEnable = false;
                showResultsBlock = false;
                returnToZipCode = true;
                return null;
        }*/ /*Zip code search is not a business requirement*/
        
        /*Check for atleast one field*/
        if(email.length()<1 && phoneNum.length()<1 && fname.length()<1 && lname.length()<1){
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter atleast ONE field'));
            AccountDispFlag=true;
            DispAccountList = false;
            newButtonEnable = false;
            showResultsBlock = false;
            return null;
        }
        
        /*Check for non empty email field and format check */
        if(email!='' && !Pattern.matches('^[a-zA-Z]+[-a-zA-Z0-9_.]*@[A-Za-z0-9.]+\\.[A-Za-z]+$', email)) {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Email is in wrong format'));
                AccountDispFlag=true;
                DispAccountList = false;
                newButtonEnable = false;
                showResultsBlock = false;
                returnToEmail = true;
                return null;
        }
        /*Email size check*/
        if(email.length()>80){
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Email too long, It should NOT be greater than 80 characters long'));
                AccountDispFlag=true;
                DispAccountList = false;
                newButtonEnable = false;
                showResultsBlock = false;
                returnToEmail = true;
                return null;
        }
        
        /*Phone length and pattern check*/
        if(phoneNum!='' && (phoneNum.length()!=10 || !Pattern.matches('^[2-9][0-9]+$',phoneNum) )){
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Enter Valid Phone number'));
                AccountDispFlag=true;
                DispAccountList = false;
                newButtonEnable = false;
                showResultsBlock = false;
                returnToPhone = true;
                return null;
        }
        
        /*Formatting the Phone number to search in database*/
        String formattedPhoneNumber='';
        if(phoneNum.length()>0 && phoneNum!=''){
            DataFormatter formatter = new DataFormatter();
            formattedPhoneNumber = formatter.phoneFormatter(phoneNum);
            if(formattedPhoneNumber=='Failed'){
                formattedPhoneNumber='';
            }
        }
        //String lastFourDigtsOfPhone = phoneNum.right(4);
        
        system.debug('Email>>>>>>>>: '+email);

        /*Creating the account search query*/
        String searchQuery = 'Select Id, FirstName, LastName, Status__c,';
        searchQuery += 'PersonEmail, Marketing_Email__pc, Other_Email_2__pc, University_Email__pc, Personal_Email__PC, Work_Email__pc, Other_Email__PC ';
        searchQuery+=',phone, PersonMobilePhone, PersonHomePhone, PersonOtherPhone, PersonAssistantPhone, work_Phone__c, marketing_Phone__PC, Other_Phone_2__pc,work_Phone__pc ';
        searchQuery+=',BillingPostalCode, ShippingPostalCode, PersonMailingPostalCode, PersonOtherPostalCode, Other_Postal_Code__c';
        searchQuery+=' from Account where RecordTypeId=\''+accountRecordType+'\''; 
        if(fname.length()>0 && fname!=''){
        // searchQuery+= ' AND FirstName LIKE \'%'+fname+'%\'';
        //Added By  suneetha on feb 16 2013
            searchQuery+= ' AND FirstName LIKE \'%'+fname.replace('\'','\\\'')+'%\'';
        }
        if(lname.length()>0 && lname!=''){
            searchQuery+= ' AND LastName LIKE \'%'+lname+'%\'';
              //Added By  suneetha on feb 16 2013
              searchQuery+= ' AND LastName LIKE \'%'+lname.replace('\'','\\\'')+'%\'';  
        }
        //if(PhoneNum!='' && PhoneNum!=null){
        if(formattedPhoneNumber.length()>0 && formattedPhoneNumber!=''){
                searchQuery += ' AND (phone LIKE \'%'+formattedPhoneNumber+'%\' OR PersonMobilePhone LIKE \'%'+formattedPhoneNumber+'%\' OR PersonHomePhone LIKE \'%'+formattedPhoneNumber+'%\' OR PersonOtherPhone LIKE \'%'+formattedPhoneNumber+'%\' OR PersonAssistantPhone LIKE \'%'+formattedPhoneNumber+'%\' OR work_Phone__c LIKE \'%'+formattedPhoneNumber+'%\' OR marketing_Phone__PC LIKE \'%'+formattedPhoneNumber+'%\' OR Other_Phone_2__pc LIKE \'%'+formattedPhoneNumber+'%\' OR work_Phone__pc LIKE \'%'+formattedPhoneNumber+'%\')';
        }
        //if(email!='' && email!=null){
        if(email.length()>0){
                searchQuery += ' AND (PersonEmail =\''+email+'\' OR Marketing_Email__pc =\''+email+'\' OR  Other_Email_2__pc =\''+email+'\' OR  University_Email__pc =\''+email+'\' OR  Personal_Email__PC =\''+email+'\' OR  Work_Email__pc =\''+email+'\' OR  Other_Email__PC =\''+email+'\')';
        }
        //if(zip!='' || zip!=null){
        /*if(zip.length()>0){
                searchQuery += ' AND (BillingPostalCode=\''+zip+'\' OR ShippingPostalCode=\''+zip+'\' OR PersonMailingPostalCode=\''+zip+'\' OR PersonOtherPostalCode=\''+zip+'\' OR Other_Postal_Code__c=\''+zip+'\') ';
        }*/ /*zip code is not a business requirement*/
        
        /*Searching in Account*/
        try{
            system.debug('THE QUERY ACCOUNT>>>>>>>> '+searchQuery);
            matchingAccounts = Database.query(searchQuery);
        }catch(QueryException qe){
            system.debug('ERROR IN ACCOUNT search query>>>>>>>>'+qe.getMessage());
        }
        if(matchingAccounts.size()>0){
            dispAccountList = true;
            showResultsBlock =true;
            //if(matchingAccounts.size()==1){  //Commented: If ANY result is found then the NewButtonEnable should be false.
                    newButtonEnable = false;
            //}
            //else{
                    //newButtonEnable = true;
            //}
            for(Integer index=0;index<matchingAccounts.size(); index++){
                    AccountValues tempObject = new AccountValues(matchingAccounts[index].FirstName, matchingAccounts[index].LastName, matchingAccounts[index].id,matchingAccounts[index].Phone,matchingAccounts[index].PersonEmail, 'Account',matchingAccounts[index].status__C);
                    AccList.add(tempObject);
            }
                    //return null; //Commented: Search should go on
        }
                //else{ //Commented: The search should Go on.. 
        /*Creating the Lead search query*/
      //  fname= fname.replace('\'','\'\\');

        searchQuery = 'Select Id, FirstName, LastName,Status,Status_Detail__c, ';
        searchQuery += 'email, Marketing_Email__c, Other_Email_2__c, University_Email__c, Personal_Email__C, Work_Email__c, Other_Email__C ';
        searchQuery+=', phone, MobilePhone, Home_Phone__c, work_Phone__c, marketing_Phone__C, Other_Phone_2__c, Other_Phone__c ';
        searchQuery+=',PostalCode, Other_Postal_code__c ';
        searchQuery+='from lead where IsConverted=false AND RecordTypeId=\''+leadRecordType+'\'';
        if(fname.length()>0 && fname!=''){
        // searchQuery+= ' AND FirstName LIKE \'%'+fname+'%\'';
          //Added By  suneetha on feb 16 2013
            searchQuery+= ' AND FirstName LIKE \'%'+fname.replace('\'','\\\'')+'%\'';
        }
        if(lname.length()>0 && lname!=''){
           // searchQuery+= ' AND LastName LIKE \'%'+lname+'%\''; 
             //Added By  suneetha on feb 16 2013
              searchQuery+= ' AND LastName LIKE \'%'+lname.replace('\'','\\\'')+'%\'';  
        }
        if(formattedPhoneNumber.length()>0 && formattedPhoneNumber!=''){
                searchQuery += ' AND (phone LIKE \'%'+formattedPhoneNumber+'%\' OR MobilePhone LIKE \'%'+formattedPhoneNumber+'%\' OR Home_Phone__c LIKE \'%'+formattedPhoneNumber+'%\' OR work_Phone__c LIKE \'%'+formattedPhoneNumber+'%\' OR marketing_Phone__C LIKE \'%'+formattedPhoneNumber+'%\' OR Other_Phone_2__c LIKE \'%'+formattedPhoneNumber+'%\' OR Other_Phone__c LIKE \'%'+formattedPhoneNumber+'%\' )';
        }
        if(email.length()>0){
                searchQuery += ' AND (email =\''+email+'\' OR Marketing_Email__c =\''+email+'\' OR  Other_Email_2__c =\''+email+'\' OR  University_Email__c =\''+email+'\' OR  Personal_Email__C =\''+email+'\' OR  Work_Email__c =\''+email+'\' OR  Other_Email__C =\''+email+'\')';
        }
        /*if(zip.length()>0){
                searchQuery += 'AND (PostalCode=\''+zip+'\' OR Other_Postal_code__c=\''+zip+'\' ) ';
        }*/ /*zip code is not a business requirement*/
                
        /*Searching in Lead*/
        try{
                system.debug('THE QUERY LEAD >>>>>>>> '+searchQuery);
                matchingLeads = Database.query(searchQuery);
        }
        catch(QueryException qe){
                system.debug('ERROR IN LEAD search query>>>>>>>>'+qe.getMessage());
        }
                
        if(matchingLeads.size()>0){
            dispAccountList = true;
            showResultsBlock =true;
            //if(matchingLeads.size()==1){//Commented: If ANY result is found then the NewButtonEnable should be false.
                    newButtonEnable = false;
            //}
            //else{
            //      newButtonEnable = true;
            //}
            String strLeadStatus ='';
            for(Integer index=0;index<matchingLeads.size(); index++){
        		strLeadStatus='';
        		if(matchingLeads[index].Status_Detail__c!= null){
        			strLeadStatus=matchingLeads[index].Status+'-'+matchingLeads[index].Status_Detail__c;
        		}else{
        			strLeadStatus=matchingLeads[index].Status;
        		}
                AccountValues tempObject = new AccountValues(matchingLeads[index].FirstName, matchingLeads[index].LastName, matchingLeads[index].id, matchingLeads[index].Phone, matchingLeads[index].email, 'Lead',strLeadStatus);
                AccList.add(tempObject);
            }
            return null;
        }
                        
        if(AccList.size()<1){

        /*No matches found, Create new Lead*/
                                
	        ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.INFO,'No Matches '));
	        //AccountDispFlag=false;
	        //DispAccountList = false;
	        newButtonEnable = true;
	        showResultsBlock = false;
	        savebuttonenable = false;
	        
	        return null;
        }
        return null;
        }

    public void reset(){
        showResultsBlock = false;
        AccList.clear();
        fname = '';
        lname = '';
        //zip = '';
        email = '';
        phoneNum = '';
        newButtonEnable = false;
    }
    
    public String SFDCLeadId{get; set;}
    
    /****TO create a new Lead****/
    public PageReference saveButtonClicked(){
        errorOccured =false;
        //saveSuccessful=false;
        
        if(fname=='' ||lname=='' ||email=='' || state==''||country==''){//Removed PhoneNum and postal code from mandatory check.
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'First Name, Last Name, Email, state and country are mandatory fields'));
                errorOccured =true;
                return null;
        }
        
        /*Check for pattern match and empty first Name and Last Name */
        if(fname!=''&& lname!='' && (!Pattern.matches('^[-a-zA-Z0-9.&#()/_\'\\s]+$', fname) || !Pattern.matches('^[-a-zA-Z0-9.&#()/_\'\\s]+$', lname))){
        //if(fname!='' && lname!='' && (!Pattern.matches('^[a-zA-Z.–&#()\'/_]+$', fname) || !Pattern.matches('^[a-zA-Z.–&#()\'/_]+$', lname))){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Names can contain only alphabetical characters'));
                errorOccured =true;
                return null;
        }
        
        /*Check for non empty zip code but with wrong values*/
        /*if(zip!='' && (!Pattern.matches('^[0-9]+$', zip)||zip.length()!=5)){
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'ZIP Code should contain 5 digits'));
                errorOccured =true;
        }*/ /*Not a business requirement*/
        
        
        /*Check for non empty email field and format check */
        if(email!='' && !Pattern.matches('^[a-zA-Z]+[-a-zA-Z0-9_.]*@[A-Za-z0-9.]+\\.[A-Za-z]+$', email)) {
        //if(email!='' && !Pattern.matches('^[a-zA-Z]+[a-zA-Z0-9_.]*@[A-Za-z0-9.]+\\.[A-Za-z]+$', email)) {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Email is in wrong format'));
                errorOccured =true;
                return null;
        }
        /*Email size check*/
        if(email.length()>80){
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Email too long. Should be less than 80 characters long'));
                errorOccured =true;
                return null;
        }
        
        /*Phone length and pattern check*/
        if(phoneNum!='' && (phoneNum.length()!=10 || !Pattern.matches('^[2-9][0-9]+$',phoneNum) )){
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Enter Valid Phone number'));
                errorOccured =true;
                return null;
        }
        
        /*State and country pattern and length check*/
        if(!Pattern.matches('^[a-zA-Z]+$', state) || state.length()>30){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Enter Valid State'));
            errorOccured =true;
            return null;
        }
        if(!Pattern.matches('^[a-zA-Z]+$', country) || country.length()>30){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Enter Valid country'));
            errorOccured =true;
            return null;
        }
        
        
        /*If all fields clear requirements, a new lead is created*/
        if(!errorOccured){
                Lead newLead = new Lead();
                newLead.FirstName = fname;
                newLead.LastName = lname;
                newLead.Personal_Email__c = email;
                newLead.State = state;
                //newLead.PostalCode=zip;
                //newLead.Program__c = programValue.Id;
                newLead.RecordTypeId = Schema.Sobjecttype.Lead.getRecordTypeInfosByName().get('West - Prospective Student').getRecordTypeId();
                newLead.Country = country;
                
                try{
                        insert newLead;
                }
                catch(DMLException de){
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Unable to create Lead'));
                        system.debug('ERROR in creating new lead>>>>>>>>>'+de.getmessage());
                        return null;
                }
                /****On successful insertion, the page is redirected to the view page of the newly created lead*****/
                
                String redirectURL = URL.getSalesforceBaseUrl().toExternalForm()+'/'+newLead.id;
                PageReference pr = new PageReference(redirectURL);
                pr.setRedirect(true);
                return pr;

                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.INFO,'Successful in creating new lead'));
        }
        return null;
    }
    
    public void newAccButtonClicked(){
        searchButtonEnable = false;
        saveButtonEnable = true;
        reqFieldsEnable = true;
        newButtonEnable = false;
        showResultsBlock = false;
    }
    
    //public String chosenId{get;set;}
    
    public Pagereference clickResultLink(){
        //String fullRecordURL = URL.getSalesforceBaseUrl().toExternalForm() + '/' + acct.Id;
        
        String chosenId = System.currentPageReference().getParameters().get('chosenId');
        String redirectURL = URL.getSalesforceBaseUrl().toExternalForm()+'/'+chosenId;
        PageReference pr = new PageReference(redirectURL);
        pr.setRedirect(true);
        return pr;

    }
    
    public list<AccountValues> getcatchAccounts(){

        return AccList;
    }

        public class AccountValues{
                public String FirstName{get; set;}
                public String LastName{get; set;}
                //public String Zip{get; set;}
                public String PrimaryPhone{get; set;}
                public String PrimaryEmail{get; set;}
                public String Id{get; set;}
                public String typeOfRecord{get; set;}
                public String status{get;set;}
                public AccountValues(String FirstName1, String LastName1,
                                                        String Id1, String PrimaryPhone1, String PrimaryEmail1, String typeOfRecord1,String strStatus){
                        FirstName = FirstName1;
                        LastName = LastName1;
                        //Zip = Zip1;
                        Id = Id1;
                        PrimaryPhone = PrimaryPhone1;
                        PrimaryEmail = PrimaryEmail1;
                        typeOfRecord = typeOfRecord1;
                        status = strStatus;
                }
        }   
}